/**
 * 路线编辑、新增
 *
 */
define(["app", "js/services/MessageBox", "js/services/MuseService",
    'js/controllers/route/route/RouteSiteSelectController',
    'js/controllers/route/route/ReverseRouteSelectController'], function (app) {

    var deps = ["$scope", "$state", "$modal", "$stateParams", "MessageBox", "MuseService"];

    function controller ($scope, $state, $modal, $stateParams, MessageBox, MuseService) {
        //获取参数
        var id = $stateParams.id || '';
        $scope.route = {
            sites: [],
            enable: true
        }

        $scope.timeRange = fillTimeRange();

        function fillTimeRange () {
            var range = [];
            var lastTime = 24 * 60 * 60 * 1000//一天最后毫秒
            var timeStep = 15 * 60 * 1000//15分钟
            for (var i = 0; i < lastTime; i += timeStep) {
                var t = {
                    'label': getTimeStr(i),
                    'value': i
                }
                range.push(t);
            }
            //增加最后一秒

            var last = lastTime - 1;
            range.push({
                'label': getTimeStr(last),
                'value': last
            });
            return range;
        }

        function getTimeStr (t) {
            t = t || 0;
            var time = new Date(t);
            var h = time.getUTCHours();
            var m = time.getUTCMinutes();
            return addPreZero(h) + ":" + addPreZero(m);
        };

        function addPreZero (num) {
            var count = 2;
            var t = (num + '').length,
                s = '';

            for (var i = 0; i < count - t; i++) {
                s += '0';
            }

            return s + num;
        }

        //获取数据
        $scope.getDetail = function () {
            MuseService.get(baseServices_restfulUrl + "route/load.json?id=" + id).success(
                function (data, status, headers, config) {
                    if (data.state == 0) {
                        $scope.route = data.data;
                    } else {
                        MessageBox.notify('获取数据失败:' + data.message);
                    }
                });
        };
        if (id) {
            $scope.getDetail();
        }

        var saveRoute = function () {
            MuseService.postObj(baseServices_restfulUrl + "route/save.json", $scope.route).success(
                function (data, status, headers, config) {
                    if (data.state == 0) {
                        $scope.result = data.data;
                        MessageBox.notify('保存成功!');
                        $state.go('routeList');
                    } else {
                        MessageBox.notify('保存失败：' + data.message);
                    }
                });
        }
        //保存
        $scope.saveObj = function () {

            if (isEmpty($scope.route.sites) || $scope.route.sites.length < 2) {
                MessageBox.notify('至少包含两个站点!');
                return;
            }

            if (isEmpty($scope.route.allowStartTime)) {
                MessageBox.notify('首班车发车时间还没设置!');
                return;
            }

            if (isEmpty($scope.route.allowEndTime)) {
                MessageBox.notify('末班车发车时间还没设置!');
                return;
            }

            if ($scope.route.allowEndTime < $scope.route.allowStartTime) {
                MessageBox.notify('运营结束时间 必须超过 运营开始时间!');
                return;
            }

            if (isEmpty($scope.route.reverseRouteId)) {
                var dialog = MessageBox.confirm('你还没选择返程路线，确定保存？');
                dialog.result.then(function () {
                    saveRoute();
                });
                return;
            }

            saveRoute();

        };


        // 取消，返回
        $scope.close = function () {
            $state.go("routeList");
        };

        var onSelectRouteSiteFun = function (routeSite) {

            var routeSiteEntity = {
                name: routeSite.name,
                routeSite: routeSite,
                route: {
                    id: $scope.route.id
                },
                sort: $scope.route.sites.length,
                cost: 0
            };

            //选择site
            console.log("选择了" + routeSite);
            var added = $scope.route.sites.indexOf(routeSiteEntity, function (a, b) {
                    return a.routeSite.id == b.routeSite.id;
                }) > -1;
            if (!added) {
                $scope.route.sites.push(routeSiteEntity);
            }
        }

        $scope.selectRouteSite = function () {

            $modal.open({
                templateUrl: 'views/route/route/routeSiteSelect.html',
                controller: 'RouteSiteSelectController',
                backdrop: 'static',
                keyboard: false,
                size: 'lg',
                resolve: {
                    onSelectRouteSite: function () {
                        return angular.copy(onSelectRouteSiteFun);
                    }
                },
                windowClass: 'app-modal-window'
            }).result.then(function () {
                //$scope.list();
            });
        };

        function sortIndex (arrayData) {
            if (arrayData && arrayData.length && arrayData.length > 0) {
                for (var i = 0; i < arrayData.length; i++) {
                    var obj = arrayData[i];
                    obj.sort = i;
                }
            }
        }

        //监听站点变化，更改顺序
        $scope.$watch('route.sites', function (newValue, oldValue) {
            sortIndex(newValue);//更新排序
        });


        $scope.sortRouteSite = function (site, direction) {
            var offset = (direction == "up") ? -1 : 1;
            $scope.route.sites.swapOffset(site, offset);
            //通知更新
            sortIndex($scope.route.sites);
        };

        $scope.removeRouteSite = function (routeSiteEntity) {
            $scope.route.sites.removeItem(routeSiteEntity);
        }

        //增加价格变化监听
        var $unWatch = $scope.$watch('getTotalCost()', function (newValue, oldValue) {
            $scope.route.cost = newValue;
        });


        $scope.getTotalCost = function () {
            var totalCost = 0;
            angular.forEach($scope.route.sites, function (routeSiteEntity) {
                totalCost += parseInt(routeSiteEntity.cost);
            });

            return totalCost;
        }

        //===========反向路线===========

        var onSelectReverseRouteFun = function (reverseRoute) {
            $scope.route.reverseRouteId = reverseRoute.id;
            $scope.route.reverseRouteName = reverseRoute.name;
        };

        $scope.selectReverseRoute = function () {

            $modal.open({
                templateUrl: 'views/route/route/reverseRouteSelect.html',
                controller: 'ReverseRouteSelectController',
                backdrop: 'static',
                keyboard: false,
                size: 'lg',
                resolve: {
                    orginRoute: function () {
                        return angular.copy($scope.route);
                    },
                    onSelectReverseRoute: function () {
                        return angular.copy(onSelectReverseRouteFun);
                    }
                },
                windowClass: 'app-modal-window'
            }).result.then(function () {
                //$scope.list();
            });
        };
    }

    controller.$inject = deps;
    app.lazy.controller("RouteEditController", controller);
});
